import * as fs from 'fs';
import jsYaml from 'js-yaml';
import type{OpenAPIV3} from 'openapi-types';

/**
 * 修正 apifox 生成但 json/yaml 文件
 * 1. 由 json 转 yaml
 * 2. 删除 header 中但 authorization，此部分由拦截器公共提供 无需再代码中提及
 * 
 */

function main() {
  const content = fs.readFileSync('src/yaml/odin加速器-前台接口.openapi.json', {encoding: 'utf-8'});
  const doc: OpenAPIV3.Document = JSON.parse(content);
  const paths = doc.paths;

  for(const pathItem in paths) {
    const pathObj = paths[pathItem];
    if(!pathObj) {
      console.warn(`${pathItem} empty, ignored`);
      continue;
    }
    // 暂时没有数据放在这里，先忽略
    // pathObj.parameters
    if(pathObj.get) {
      fixOperationObject(pathObj.get);
    }
    if(pathObj.put) {
      fixOperationObject(pathObj.put);
    }
    if(pathObj.post) {
      fixOperationObject(pathObj.post);
    }
    if(pathObj.head) {
      fixOperationObject(pathObj.head);
    }
    if(pathObj.delete) {
      fixOperationObject(pathObj.delete);
    }
    if(pathObj.patch) {
      fixOperationObject(pathObj.patch);
    }
    if(pathObj.options) {
      fixOperationObject(pathObj.options);
    }
    if(pathObj.trace) {
      fixOperationObject(pathObj.trace);
    }
  }
  // 转 yaml
  const yrs = jsYaml.dump(doc);
  fs.writeFileSync('src/yaml/odin-api-v1.yaml', yrs, {encoding: 'utf-8'});
  console.log('finished');
}

function fixOperationObject(v: OpenAPIV3.OperationObject) {
  const parameters = v.parameters;
  // 后端接口分了目录，生成接口时不需要这个tags和x-apifox-folder，有这个字段存在会报错
  if (v.tags!?.length > 0) {
    v.tags = [];
  }
  // @ts-ignore
  if (v['x-apifox-folder']) {
    // @ts-ignore
    v['x-apifox-folder'] = "";
  }
  if(!parameters) {
    // not have a parameters, ignored
    return;
  }
  const pos = parameters.findIndex(parItem => {
    if('$ref' in parItem) {
      return false;
    }
    if(parItem.in.toLowerCase() === 'header' && parItem.name.toLowerCase() === 'authorization') {
      return true;
    }
    return false;
  });
  if(pos === -1) {
    return;
  }
  parameters.splice(pos, 1);
}

main();
